package org.example.cake.controller;

import org.example.cake.common.Rep;
import org.example.cake.dto.BuyCarRequest;
import org.example.cake.entity.Buycar;
import org.example.cake.service.BuycarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.cake.common.Rep;
import org.example.cake.common.Repsecond;
import org.example.cake.entity.Buycar;
import org.example.cake.service.BuycarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/buycar")
public class BuycarController {
    @Autowired
    private BuycarService buycarService;

    /**
     * 新增购物车
     * @param buycar 购物车信息
     * @Date 2025-07-31 谭丽娜
     * @return
     */
    @PostMapping("/addBuyCar")
    public Rep addBuyCarqian(@RequestBody Buycar buycar) {
        String meg="200";
        Integer res=0;
        //判断购物车是否有这个蛋糕
        Integer flag=buycarService.selectBuyCarifhas(buycar);
        if(flag>0){
            //查询蛋糕是否是限购
            Integer cakecaount=buycarService.selectcakecount(buycar);
            //在原本的购物车上进行修改
            if(cakecaount<3){
                //修改蛋糕数量
                buycarService.updatebuycarCount(buycar);
            }else {
                meg="222";
            }

        }else {
            res=buycarService.addBuyCarapi(buycar);
        }
        return new Rep().addData("res",res).addData("meg",meg);
    }

    /**
     * 查询购物车以及结算信息
     * @Date 2025-07-31 谭丽娜
     * @param userid 用户id
     * @return
     */
    @GetMapping("/selectBuyCar")
    public Rep selectBuyCarqian(@RequestParam("userid")Integer userid){
        //查询购物车以及计算总金额
        List<BuyCarRequest> buycarRep=buycarService.selectBuycarListapi(userid);
        return  new Rep().addData("buycarRep",buycarRep);
    }

    /**
     * 修改购物车数量
     * @param buycar
     * @Date 2025-07-31 谭丽娜
     * @return
     */
    @PostMapping("updateCount")
    public Rep updateCountqian(@RequestBody Buycar buycar){
        Integer res=buycarService.updateCountapi(buycar);
        return new Rep().addData("res",res);
    }

    /**
     * 删除购物车
     * @param buyid
     * @Date 2025-07-31 谭丽娜
     * @return
     */
    @PostMapping("/deleteBuyapi")
    public Rep deleteBuyapi(@RequestBody Integer buyid){
        Integer res=buycarService.deleteBuyapi(buyid);
        return new Rep().addData("res",res);
    }

    /**
     * 删除所有的购物车
     * @param userid 用户id
     * @Date 2025-07-31 谭丽娜
     * @return
     */
    @PostMapping("/deletAllBuyApi")
    public Rep deletAllBuyApi(@RequestBody Integer userid){
        Integer res=buycarService.deleteBuyAllapi(userid);
        return new Rep().addData("res",res);
    }

    /**
     * 立即购买
     * @param buycar
     * @Date 2025-07-31 谭丽娜
     * @return
     */
    @PostMapping("/nowBuy")
    public Rep nowBuy(@RequestBody Buycar buycar){
        BuyCarRequest buyCarRequest=buycarService.getcakeNow(buycar);
        return new Rep().addData("buyCarRequest",buyCarRequest);
    }
    /**
     * 前端查询所有购物车数据
     * @return 统一响应格式
     */
    @GetMapping("/selectBuycarDetails")
    public Rep getBuycarListFront(@RequestParam("page") Integer page,
                                  @RequestParam("pageSize") Integer pageSize) {
        // 开启分页
        PageHelper.startPage(page, pageSize);
        // 执行查询
        List<Map<String, Object>> buycarList = buycarService.getBuycarDetails();
        // 创建分页对象
        PageInfo<Map<String, Object>> buycarPageInfo = new PageInfo<>(buycarList);
        // 返回
        return new Rep().addData("buycarPageInfo", buycarPageInfo);
    }

    /**
     * 根据用户名称蛋糕名称查询购物车
     * @param page
     * @param pageSize
     * @param searchKey
     * @return
     */
    @GetMapping("/selectBuycarDetailsBySearch")
    public Rep selectBuycarDetails(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestParam(required = false) String searchKey) {

        // 1. 查询数据列表
        List<Map<String, Object>> list = buycarService.getBuycarDetailsBySearch(page, pageSize, searchKey);

        // 2. 查询总条数
        Integer total = buycarService.countBuycarDetailsBySearch(searchKey);

        // 3. 封装分页结果
        Map<String, Object> pageInfo = new HashMap<>();
        pageInfo.put("list", list);
        pageInfo.put("total", total);
        pageInfo.put("pageSize", pageSize);
        pageInfo.put("currentPage", page);

        return new Rep().addData("buycarPageInfo", pageInfo);
    }
    /**
     * 查询所有购物车数据
     * @return 所有购物车数据
     */
    @GetMapping("/selectAllBuycar")
    public Rep selectAllBuycar() {
        List<Map<String, Object>> listBuycar = buycarService.getBuycarDetails();
        return new Rep().addData("listBuycar", listBuycar);
    }

    /**
     * 根据用户ID查询购物车
     * @param userId 用户ID
     * @return 购物车列表
     */
    @GetMapping("/seBuycarByUserId")
    public Rep selectBuycarsByUserId(@RequestParam("page") Integer page,
                                     @RequestParam("pageSize") Integer pageSize,
                                     @RequestParam("userId") Integer userId) {
        // 开启分页
        PageHelper.startPage(page, pageSize);
        // 执行查询
        List<Map<String, Object>> buycarList = buycarService.getBuycarDetailsByUserId(userId);
        // 创建分页对象
        PageInfo<Map<String, Object>> buycarPageInfo = new PageInfo<>(buycarList);
        // 返回
        return new Rep().addData("buycarPageInfo", buycarPageInfo);
    }

    /**
     * 根据蛋糕ID查询购物车
     * @param cakeId 蛋糕ID
     * @return 购物车列表
     */
    @GetMapping("/seBuycarByCakeId")
    public Rep selectBuycarsByCakeId(@RequestParam("page") Integer page,
                                     @RequestParam("pageSize") Integer pageSize,
                                     @RequestParam("cakeId") Integer cakeId) {
        // 开启分页
        PageHelper.startPage(page, pageSize);
        // 执行查询
        List<Map<String, Object>> buycarList = buycarService.getBuycarDetailsByCakeId(cakeId);
        // 创建分页对象
        PageInfo<Map<String, Object>> buycarPageInfo = new PageInfo<>(buycarList);
        // 返回
        return new Rep().addData("buycarPageInfo", buycarPageInfo);
    }


    /**
     * 查询所有购物车数据
     * @return 统一响应格式
     */
    @GetMapping("/getBuycarList")
    public Repsecond getBuycarList() {
        try {
            List<Map<String, Object>> buycarList = buycarService.getBuycarDetails();
            return new Repsecond()
                    .addData("buycarList", buycarList)
                    .addData("count", buycarList.size());
        } catch (Exception e) {
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("查询购物车列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取购物车详情
     * @param buyId 购物车ID
     * @return 统一响应格式
     */
    @GetMapping("/{buyId}")
    public Repsecond getBuycarById(@PathVariable Integer buyId) {
        try {
            Map<String, Object> buycar = buycarService.getBuycarDetailsByUserAndCake(null, null)
                    .stream()
                    .filter(b -> b.get("buyId").equals(buyId))
                    .findFirst()
                    .orElse(null);

            if (buycar == null) {
                return new Repsecond()
                        .setCode(404)
                        .setMsgerr("购物车记录不存在");
            }
            return new Repsecond()
                    .addData("buycar", buycar);
        } catch (Exception e) {
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("获取购物车详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新购物车信息
     * @param buycar 购物车实体
     * @return 统一响应格式
     */
    @PostMapping("/updateBuycar")
    public Repsecond updateBuycar(@RequestBody Buycar buycar) {
        try {
            if (buycar.getBuyid() == null) {
                return new Repsecond()
                        .setCode(400)
                        .setMsgerr("购物车ID不能为空");
            }

            boolean result = buycarService.updateBuycar(buycar);
            if (result) {
                return new Repsecond()
                        .setMsgerr("更新成功");
            }
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("更新失败");
        } catch (Exception e) {
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("更新购物车失败: " + e.getMessage());
        }
    }

    /**
     * 删除购物车记录
     * @param buyId 购物车ID
     * @return 统一响应格式
     */
    @DeleteMapping("/{buyId}")
    public ResponseEntity<Map<String, Object>> deleteBuycar(@PathVariable Integer buyId) {
        // 1. 参数验证
        if (buyId == null || buyId <= 0) {
            return ResponseEntity.badRequest().body(Map.of(
                    "code", 400,
                    "message", "购物车ID必须为正整数"
            ));
        }

        // 3. 执行业务逻辑
        try {
            boolean result = buycarService.deleteBuycar(buyId);
            if (result) {
                return ResponseEntity.ok(Map.of(
                        "code", 200,
                        "message", "删除成功"
                ));
            }
            return ResponseEntity.status(500).body(Map.of(
                    "code", 500,
                    "message", "删除失败"
            ));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                    "code", 500,
                    "message", "删除失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 批量删除购物车记录
     * @param buyIds 购物车ID列表
     * @return 统一响应格式
     */
    @DeleteMapping("/batch")
    public Repsecond batchDeleteBuycar(@RequestBody List<Integer> buyIds) {
        try {
            if (buyIds == null || buyIds.isEmpty()) {
                return new Repsecond()
                        .setCode(400)
                        .setMsgerr("参数不能为空");
            }

            int successCount = buycarService.batchDeleteBuycar(buyIds);
            return new Repsecond()
                    .setMsgerr("批量删除完成")
                    .addData("successCount", successCount)
                    .addData("totalCount", buyIds.size());
        } catch (Exception e) {
            return new Repsecond()
                    .setCode(500)
                    .setMsgerr("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 查询购物车里购物总数有木有
     * @Date 2025-08-11 谭丽娜
     * @param cakeid
     * @return
     */
    @PostMapping("/selectBuycarhascount")
    public  Rep selectBuycarhascount(@RequestBody Integer cakeid){
        Integer res=buycarService.cakecount(cakeid);
        return new Rep().addData("res", res);
    }

    /**
     * 根据蛋糕id修改购物车数量
     * @param buycar
     * @return
     */
    @PostMapping("/updateCountCakeid")
    public  Rep updateCountCakeid(@RequestBody Buycar buycar){
        Integer res=buycarService.updateCountCakeid(buycar);
        return new Rep().addData("res", res);
    }
}
